﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Messhall.Application.Dto;
using Messhall.Application.Dto.Users;
using Messhall.Application.Dto.Users.Responses;
using Messhall.Domain.Permission.BusinessObjects;
using Messhall.Domain.Permission.IRepositorys;
using Messhall.Framework;
using Messhall.Framework.EntityFrameworkCore;
using Messhall.Framework.Repository.Repositorys;
using Messhall.Framework.Repository.UnitOfWork;
using Microsoft.EntityFrameworkCore;

namespace Messhall.Repository.Permission.Repositorys
{
    public class UsersRepository : RepositoryBase<Users, UsersEntity>, IUsersRepository
    {
        public UsersRepository(IDbContextUnitOfWork dbContext) : base(dbContext)
        {
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagingResponseBase<UserPagingResponse>> PagingAsync(UserPagingRequest request)
        {
            var userQuery = base.Set<UsersEntity>();

            Expression<Func<UsersEntity, bool>> predicate = user => true;

            if (!string.IsNullOrWhiteSpace(request.LikeName))
            {
                predicate.And(user => user.Name.Contains(request.LikeName));
            }

            if (!string.IsNullOrWhiteSpace(request.Mobile))
            {
                predicate.And(user => user.Mobile.Contains(request.Mobile));
            }

            var userData = await userQuery.Where(predicate).Select(user => new UserPagingResponse
            {
                AccountNo = user.AccountNo,
                CreateTime = user.CreateTime,
                Integral = user.Integral,
                IsVip = user.IsVip,
                KeyId = user.KeyId,
                Mobile = user.Mobile,
                Money = user.Money,
                Name = user.Name,
                UpdateTime = user.UpdateTime,
            }).OrderByDescending(user => user.CreateTime).PagingAsync(request.PageIndex, request.PageSize);

            return new()
            {
                Data = userData.Item1, PageIndex = request.PageIndex, PageSize = request.PageSize,
                TotalCount = userData.Item2
            };
        }
    }
}